package com.pinyoumei.mq;

import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.pinyoumei.adapter.MessageAdapter;
import com.pinyoumei.constans.Constants;
import com.pinyoumei.handler.EmailService;

import lombok.extern.slf4j.Slf4j;


/**
 * RabbitMQ消费者，只需要对应的方法上加入 @RabbitListener 注解，指定需要监听的队列名称即可。
 * @author peter
 *
 */
@Slf4j
@Component
public class Consumer {
	
	@Autowired
	private EmailService emailService;
	
	private MessageAdapter messageAdapter;
	
	private final static String QUEUE_NAME="member-email-queue";
	
	//监听队列
	@RabbitListener(queues=QUEUE_NAME)
	public void consumeMessage(String json) {
       log.info("*********Consumer收到消息:"+json+"**********");
       if (StringUtils.isEmpty(json)) {
			return;
		}
       JSONObject rootJson = new JSONObject().parseObject(json);
	   JSONObject header = rootJson.getJSONObject("header");
		String interfaceType = header.getString("interfaceType");
		if (StringUtils.isEmpty(interfaceType)) {
			return;
		}
		// 判断接口类型是否为发邮件
		if (interfaceType.equals(Constants.MSG_EMAIL)) {
			messageAdapter = emailService;
		}
		if (messageAdapter == null) {
			return;
		}
		JSONObject contentJson = rootJson.getJSONObject("content");
		messageAdapter.sendMsg(contentJson);
    }

}
